//
//  SelectContractorViewController.m
//  FMS
//
//  Created by Steven on 10/19/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "SelectContractorViewController.h"
#import "ScheduleInspectionViewController.h"

@interface SelectContractorViewController ()

@end

@implementation SelectContractorViewController
@synthesize parent;
@synthesize inputInspectionDict;
@synthesize inputMaintenanceDict;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        parent = _parent;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    // Do any additional setup after loading the view from its nib.
    _lbMainTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.select-contractor.title"];
    _lbRequestTypeTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.select-contractor.request-type"];
    
    [_btnSelectContractor setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_btnSelectContractor setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
    _btnSelectContractor.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _btnSelectContractor.layer.borderWidth = 1;
    
    [_btnSelectContractor setTitle:[dictLanguage objectForKey:@"maintenance-mgmt.select-contractor.button-title"] forState:UIControlStateNormal];
    
    //add drop down image to end of button
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
    imgView.frame = CGRectMake(330, 11, 13, 8);
    [_btnSelectContractor addSubview:imgView];
    
    //set style for send button
    [_btnSend setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnSend setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateNormal];
    [_btnSend setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateHighlighted];
    _btnSend.layer.borderWidth  = 1;
    _btnSend.layer.borderColor  = [UIColor whiteColor].CGColor;
    
    int maintenanceType = [[inputMaintenanceDict objectForKey:@"maintenanceTypeId"] intValue];

    NSString *maintenanceName = [ApplicationDelegate getMaintenanceName:maintenanceType];
    
    _lbRequestType.text = maintenanceName;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (SYSTEM_VERSION_LESS_THAN(@"7.0")) ;
    else
        self.navigationController.view.superview.bounds = CGRectMake(0, 0, 400, 260);
}

- (IBAction)backPreviousView:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)handleSelectContractor:(UIButton *)sender {
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_contractor];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)handleSendAction:(id)sender {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //firstly, we check this view was loaded from Inspection failed or not.
    //if failed, we add new maintenance first, then add new inspection and assign maintenance id to this inspection document.
    //itemId <=> roomId or equipmentId depend on the type which we selected before.
    
    //attach contractor info to maintenance
    [inputMaintenanceDict setObject:_contractorDict forKey:@"contractor"];
    [inputMaintenanceDict setObject:[NSNumber numberWithInt:WAITING_FOR_COSTING] forKey:@"status"];
    [inputMaintenanceDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
    NSError *error;
    [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:inputMaintenanceDict error:&error];
    if (error != nil) {
        //failed
        NSLog(@"add maintenance failed");
    }
    else {
        //success
        //check isInspectionFailed status, add new inspection document
        BOOL isInspectionFailed = [[userDefaults objectForKey:IS_INSPECTION_FAILED] boolValue];
        if (isInspectionFailed) {
            [inputInspectionDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
            [inputInspectionDict setObject:[inputMaintenanceDict objectForKey:@"_id"] forKey:@"maintenanceId"];
            if ([CouchBaseLiteLib addNewInspection:inputInspectionDict]) {
                //add new Inspection successed
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:[dictLanguage objectForKey:@"maintenance-mgmt.select-contractor.send-message.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
            }
        }
        else {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:[dictLanguage objectForKey:@"maintenance-mgmt.select-contractor.send-message.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
        }
        
        //add new schedule
        [(ScheduleInspectionViewController*)parent saveScheduleAfterUpdateMaintenance:inputMaintenanceDict];
    }
}

#pragma mark FilterViewDelegate
- (void) didSelectFilter:(NSMutableDictionary *)filterDict {
    _contractorDict = filterDict;
    [_btnSelectContractor setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
    [popoverController dismissPopoverAnimated:YES];
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self dismissModalViewControllerAnimated:YES];
    [(ScheduleInspectionViewController*)parent finishUpdateMaintenance];
}

@end
